using Microsoft.EntityFrameworkCore;
using net_work.Config;
using net_work.Data.DTO.System;
using net_work.Data.Entity.System;
using net_work.IRepository.System;

namespace net_work.Repository.System;

public class FileRepository(ApplicationDbContext dbContext) : Repository<MyFile>(dbContext), IFileRepository
{
    public async Task<int> UploadFile(FileUseAddRequest fileUseAddRequest, MyFileAddRequest myFileAddRequest)
    {
        var fileUses = dbContext.FileUses.Where(x =>
            x.BusinessId == fileUseAddRequest.BusinessId && x.BusinessCode == fileUseAddRequest.BusinessCode).ToList();
        if (fileUses.Count <= 0)
        {
            await dbContext.FileUses.AddAsync(new FileUse
            {
                BusinessId = fileUseAddRequest.BusinessId,
                BusinessCode = fileUseAddRequest.BusinessCode
            });
            await dbContext.SaveChangesAsync();
        }

        var fileUse = dbContext.FileUses.Where(x =>
                x.BusinessId == fileUseAddRequest.BusinessId && x.BusinessCode == fileUseAddRequest.BusinessCode)
            .ToList().First();

        await dbContext.MyFiles.AddAsync(new MyFile()
        {
            FilePath = myFileAddRequest.FilePath,
            FileName = myFileAddRequest.FileName,
            FileType = myFileAddRequest.FileType,
            FileUseId = fileUse.Id
        });
        return await dbContext.SaveChangesAsync();
    }

    public async Task<List<MyFile>> GetFileList(FileUseAddRequest fileUseAddRequest)
    {
        var fileUses = dbContext.FileUses.Where(x =>
            x.BusinessId == fileUseAddRequest.BusinessId && x.BusinessCode == fileUseAddRequest.BusinessCode).ToList();
        if (fileUses.Count <= 0)
        {
            return [];
        }

        return await dbContext.MyFiles.Where(x => x.FileUseId == fileUses.First().Id).ToListAsync();
    }
}